const Koa = require('koa');
const bundle = require('./dist/vue-ssr-server-bundle.json');
const clientManifest = require('./dist/vue-ssr-client-manifest.json');
const { createBundleRenderer } = require('vue-server-renderer')
const renderer = createBundleRenderer(bundle, {
  runInNewContext: false, // 推荐
  clientManifest // （可选）客户端构建 manifest
})
const app = new Koa();

// x-response-time

app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  ctx.set('X-Response-Time', `${ms}ms`);
});

// logger

app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});

app.use(async ctx => {
  const context = {url: ctx.request.url}

  renderer.renderToString(context,(err, html) => {
    if (err) {
      if (err.code === 404) {
        ctx.response.body = 'Page not found'
      } else {
        ctx.response.body = 'Internal Server Error'
      }
    } else {
      ctx.response.body = html
    }
  })
  
});

app.listen(8091);